import io.netty.bootstrap.ServerBootstrap
import io.netty.channel.ChannelInitializer
import io.netty.channel.nio.NioEventLoopGroup
import io.netty.channel.socket.SocketChannel
import io.netty.channel.socket.nio.NioServerSocketChannel
import io.netty.handler.codec.serialization.{ClassResolvers, ObjectDecoder, ObjectEncoder}

/**
  * Created by IntelliJ IDEA.
  * Programmer : John Zn
  * Date : 2016/4/14 0014
  * Time : 22:10
  * Discribtion : 
  */
class NettyServer {
  def bind(host: String, port: Int): Unit = {
    //创建两个线程池
    val connectGroup=new NioEventLoopGroup()
    val msgGroup=new NioEventLoopGroup()

    try {
      val serverBootStrap = new ServerBootstrap()
      serverBootStrap.group(connectGroup, msgGroup).channel(classOf[NioServerSocketChannel]).childHandler(new ChannelInitializer[SocketChannel] {
        override def initChannel(ch: SocketChannel): Unit = {
          ch.pipeline().addLast(
            new ObjectEncoder,
            new ObjectDecoder(ClassResolvers.cacheDisabled(getClass.getClassLoader)),
            new ServerHandler
          )
        }
      })
      //绑定端口，调用sync方法等待绑定操作完成
      val channelFuture = serverBootStrap.bind(host, port).sync()
      //等待服务关闭
      channelFuture.channel().closeFuture().sync()
    } finally {
      //优雅的退出，释放线程池资源
      connectGroup.shutdownGracefully()
      msgGroup.shutdownGracefully()
    }
  }
}

object NettyServer {
  def main(args: Array[String]) {
    val host = args(0)
    val port = args(1).toInt
    val server = new NettyServer
    server.bind(host, port)
  }
}
